﻿using BUGCOME.Infrastructure.Attribute;
using BUGCOME.Model;
using BUGCOME.Model.Auth;
using BUGCOME.Model.Auth.dto;
using BUGCOME.Model.Enum.User;
using BUGCOME.Repository;
using BUGCOME.Service.Auth.IServices;
using Mapster;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BUGCOME.Service.Auth
{
    /// <summary>
    /// 用户消息Service业务层处理
    /// </summary>
    [AppService(ServiceType = typeof(IUserMsgService), ServiceLifetime = LifeTime.Transient)]
    public class UserMsgService : BaseService<UserMsg>, IUserMsgService
    {
        /// <summary>
        /// 异步获取用户消息分页列表
        /// </summary>
        /// <param name="parm">消息查询参数 DTO</param>
        /// <returns>分页的用户消息 DTO 列表</returns>
        public async Task<PagedInfo<UserMsgDto>> GetListAsync(UserMsgQueryDto parm)
        {
            // 根据查询参数生成查询条件表达式
            var predicate = QueryExp(parm);
            // 当消息类型为评论或点赞时
            if (parm.MsgType == UserMsgType.COMMENT || parm.MsgType == UserMsgType.PRAISE)
            {
                // 关联查询用户基础信息，转换为包含用户信息的 UserMsgDto，返回分页结果
                return await Queryable()
                .Where(predicate.ToExpression())
                .Includes(x => x.UserBase) // 关联用户基础信息
                .Select((it) => new UserMsgDto()
                {
                    User = it.UserBase.Adapt<UserBaseDto>() // 映射用户信息到 DTO
                }, true)
                .ToPageAsync(parm); // 转换为分页结果
            }
            else
            {
                // 其他消息类型，转换为不包含用户信息的 UserMsgDto，返回分页结果
                return await Queryable()
                .Where(predicate.ToExpression())
                .Select(it => new UserMsgDto()
                {
                    // 此处可根据实际需求补充其他属性映射
                }, true)
                .ToPageAsync(parm); // 转换为分页结果
            }
        }

        /// <summary>
        /// 查询导出表达式
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        private static Expressionable<UserMsg> QueryExp(UserMsgQueryDto parm)
        {
            var predicate = Expressionable.Create<UserMsg>();

            predicate = predicate.AndIF(parm.UserId != null, it => it.UserId == parm.UserId);
            predicate = predicate.AndIF(parm.IsRead != null, it => it.IsRead == parm.IsRead);
            predicate = predicate.AndIF(parm.MsgType != null, it => it.MsgType == parm.MsgType);
            //predicate = predicate.AndIF(parm.ClassifyId != null, it => it.ClassifyId == parm.ClassifyId);
            return predicate;
        }
    }
}